
/**
 * @Title: MemberServiceImpl.java
 * @Package: com.aft.cdcb.modules.member.service.impl
 * @Description: TODO
 * @author Mandarava
 * @date 2016年9月1日 下午4:23:50
 * @version 1.3.1
 * @Email wuyan1688@qq.com
 */

package com.aft.terra.modules.member.service.impl;

import com.aft.terra.app.Constants;
import com.aft.terra.common.bean.Message;
import com.aft.terra.common.utils.CommonUtil;
import com.aft.terra.common.utils.DateUtil;
import com.aft.terra.common.utils.RequestUtil;
import com.aft.terra.modules.basic.SystemConfiguration;
import com.aft.terra.modules.member.controller.MemberController;
import com.aft.terra.modules.member.model.Wechat;
import com.aft.terra.modules.member.service.MemberService;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author Mandarava
 * @date 2016年9月1日 下午4:23:50
 * @version V1.3.1
 */

public class MemberServiceImpl implements MemberService {

    /**
     * 微信授权登陆step1获取授权登陆url并设置对应请求参数
     *
     * @author Mandarava
     * @return
     */
    public String weixinOauth2Url(String userId) {
        String url = (url = Constants.WEIXIN_OAUTH2_URL).replace("APPID", SystemConfiguration.getWxAppId())
                .replace("REDIRECT_URI", SystemConfiguration.getRedirectUri()).replace("SCOPE", "snsapi_userinfo")
                .replace("STATE", StrKit.notBlank(userId) ? userId+"-http://fknz.changcl.com/login" : "http://fknz.changcl.com/login");
//				.replace("STATE", "http://ly.dev.aft100.com/login");
        return url;
    }

    /**
     * 微信登陆回调
     *
     * @author Mandarava
     * @return
     */
    public Message weixinLogin(MemberController member) {
        RequestUtil.ip(member.getRequest());
        // 微信授权登陆step2 根据回调code值 获取 access_token
        // 注意 此access_token 非彼access_token，
        // 这是专门针对微信授权登陆step1中返回的code值获取的access_token
        Message message = new Message();
        String code = member.getPara("code");
        ApiConfig apiConifg = SystemConfiguration.getApiConfig();
        ApiResult result = UserApi.getOauth2AccessToken(code, apiConifg);
        // 请求是否成功
        if (result.isSucceed()) {
            String accessToken = result.getStr("access_token");
            String openId = result.getStr("openid");
            String refreshToken = result.getStr("refresh_token");

            // access_token是否有效，无效则刷新
            if (!UserApi.validatorAccessToken(accessToken, openId)) {
                result = UserApi.refreshAccessToken(apiConifg.getAppId(), refreshToken);
                accessToken = result.getStr("access_token");
                openId = result.getStr("openid");
                refreshToken = result.getStr("refresh_token");
            }
            // 获取用户信息
            ApiResult userInfo = UserApi.getUserInfo(accessToken, openId);
            if (userInfo.isSucceed()) {
                Wechat wechat = formatUser(userInfo, null);
                Wechat existsUser = Wechat.dao.findByOpenId(wechat.getOpenId());
                wechat = (existsUser == null ? save(wechat, member.getRequest())
                        : update(formatUser(userInfo, existsUser), member.getRequest()));
                message.setSuccess(Boolean.TRUE);
                message.setMessage("授权登陆成功");
//                LogKit.info(wechat.getId() + " 微信 id");
//                User user = User.dao.queryUser(wechat.getId());
//                LogKit.info(user == null ? "用户没了" : "有了");
//                Boolean notUserBoolean = false;
//                if (user != null) {
//                    if (StringUtils.isNotBlank(user.getPhone())) {
//                        notUserBoolean = false;
//                    } else {
//                        notUserBoolean = true;
//                    }
//                } else {
//                    notUserBoolean = true;
//                }
//                Cache cache = RedisKit.getCache();
//                cache.set(Constants.WECHAT_MISSION_PHONE + wechat.getId(), notUserBoolean);
//                member.setAttr("notUser", notUserBoolean);
                message.setObject(wechat);
            }
        } else {
            message.setSuccess(result.isSucceed());
            message.setMessage(result.getErrorMsg());
        }
        return message;
    }

    private Wechat formatUser(ApiResult userInfo, Wechat wechat) {
        String[] columns = new String[]{"nickname", "sex", "province", "city", "country", "headimgurl"};
        if (wechat == null) {
            wechat = new Wechat();
        }
        for (String str : columns) {
            wechat.set("w_" + str, userInfo.get(str));
        }
        @SuppressWarnings("unchecked")
        List<String> list = userInfo.getList("privilege");
        if (!list.isEmpty()) {
            StringBuilder privilege = new StringBuilder();
            for (String str : list) {
                privilege.append(str).append(",");
            }
            wechat.setWPrivilege(privilege.substring(0, privilege.lastIndexOf(",")));
        }
        wechat.setOpenId(userInfo.getStr("openid"));
        wechat.setUnionId(userInfo.getStr("unionid"));
        return wechat;
    }

    private Wechat save(Wechat wechat, HttpServletRequest request) {
        String nickName = wechat.getStr("w_nickname").replaceAll("[^\\u0000-\\uFFFF]", "□");
        wechat.set("id", CommonUtil.getUUID()).set("createDate", DateUtil.date()).set("w_nickname", nickName)
                .set("w_last_login_ip", RequestUtil.ip(request)).set("w_last_login_time", DateUtil.date()).save();
        return wechat;
    }

    private Wechat update(Wechat wechat, HttpServletRequest request) {
        String nickName = wechat.getStr("w_nickname").replaceAll("[^\\u0000-\\uFFFF]", "□");
        wechat.set("modifyDate", DateUtil.date()).set("w_last_login_ip", RequestUtil.ip(request))
                .set("w_nickname", nickName).set("w_last_login_time", DateUtil.date()).update();
        return wechat;
    }

}
